import base64
import hashlib
import time

import rsa
import yaml

from commons.base_url_util import read_ini
from config import setting


class DebugTalk:
    def read_yaml(self,key):
        with open(setting.extract_name, encoding='utf-8') as f:
            value = yaml.safe_load(f)
            return value[key]

    # 读取环境url
    def read_env(self,key):
        return read_ini()[key]

    def add(self, a, b):
        return int(a)+int(b)

    def get_random_number(self):
        return str(int(time.time()))

    def md5_encode(self,data):
        # 把data转换为utf-8格式
        data = str(data).encode("utf-8")
        md5_value = hashlib.md5(data).hexdigest()
        return md5_value

    def base64_encode(self,data):
        # 把data转换为utf-8格式
        data = str(data).encode("utf-8")
        base64_value = base64.b64encode(data).decode(encoding="utf-8")
        return base64_value

    # 生成RSA公钥和私钥
    def create_key(self):
        (public_key, private_key)= rsa.newkeys(1024)
        with open("./public.pem","w+") as f:
            f.write(public_key.save_pkcs1().decode())
        with open("./privite.pem","w+") as f:
            f.write(private_key.save_pkcs1().decode())

    # RSA解密
    def ras_encode(self,data):
        # 加载公钥
        with open("./public.pem") as f:
            pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
        # 把data转化成utf-8的编码格式
        data = str(data).encode("utf-8")
        #把字符串加密成byte类型
        byte_value = rsa.encrypt(data,pubkey)
        #把字节转化成字符串格式
        rsa_value = base64.b64encode(byte_value).decode("utf-8")
        return rsa_value

# if __name__ == '__main__':
#     print(DebugTalk().md5_encode("admin"))